//
//  AppDelegate.m
//  Only Love
//
//  Created by 郭健 on 16/5/11.
//  Copyright © 2016年 海城. All rights reserved.
//

#import "AppDelegate.h"
#import "CurrentUserInfo.h"
#import "LoginViewController.h"
#import "MainTabBarController.h"
@interface AppDelegate ()
@property (nonatomic,retain)UITabBarController *mainTabBarController;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"970605308#six-pointedstar" apnsCertName:nil];
    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];

    

   
    return YES;
}

#pragma mark -- 监听回调
/** 用户A发送加用户B为好友的申请，用户B会收到这个回调*/

//收到好友申请
-(void)didReceiveFriendInvitationFromUsername:(NSString *)aUsername message:(NSString *)aMessage{
    
    //同意对方申请
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:aUsername message:aMessage delegate:self cancelButtonTitle:@"拒绝" otherButtonTitles:@"接受", nil];
    alertView.tag = 1000;
    [alertView show];
    //拒绝对方申请
    
}

#pragma mark -- 会话代理方法的实现
//收到普通消息的回调方法
-(void)didReceiveMessages:(NSArray *)aMessages{
    
    //通过通知中心将收到的消息们传递到聊天界面
    [[NSNotificationCenter defaultCenter]postNotificationName:@"receiveMessages" object:aMessages];
}

#pragma mark -- EMClient代理方法
//自动登录的代理方法
-(void)didAutoLoginWithError:(EMError *)aError{
    
    if (aError) {
//        NSLog(@"自动登录失败 -- %d",aError.code);
        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"提示" message:@"登录异常,为了账户安全，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        
        //登录出现问题，由于需要重新登录，所以需要将本地存储的用户信息清空
        CurrentUserInfo *currentUserInfo  = [CurrentUserInfo sharedCurrentUserInfo];
        currentUserInfo.userName = @"";
        currentUserInfo.pwd = @"";
        currentUserInfo.isLogin = NO;
    }else{
//        NSLog(@"自动登录成功 -- %d",aError.code);
        //只有自动登录成功，才算真正的登录成功，这个时候我们才可以做其他操作,在此处发送广播消息，告知需要知道的消息，登录成功的消息
        [[NSNotificationCenter defaultCenter] postNotificationName:@"successLogin" object:nil];
    }
}

#pragma mark -- ContactManager 好友申请处理结果回调
//申请好友被拒绝
-(void)didReceiveDeclinedFromUsername:(NSString *)aUsername{
    
    NSLog(@"我被%@拒绝了",aUsername);
}
//对方接受好友申请执行的代理方法
-(void)didReceiveAgreedFromUsername:(NSString *)aUsername{
    
    NSLog(@"%@接受了你的好友申请",aUsername);
}
//对方同意好友申请之后，双方都会收到该条回调
- (void)didReceiveAddedFromUsername:(NSString *)aUsername{
    
    NSLog(@"双方好友关系建立");
}


#pragma mark -- alertView 的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag == 1000) {        //被申请好友的弹窗
        if (buttonIndex == 0) {     //点击了拒绝按钮
//            [[EaseMob sharedInstance].contactManager declineInvitationForUsername:alertView.title];
            EMError *error = nil;
            BOOL isSuccess = [[EaseMob sharedInstance].chatManager rejectBuddyRequest:@"8001" reason:@"111111" error:&error];
            if (isSuccess && !error) {
                NSLog(@"发送拒绝成功");
            }
        }else{      //点击了接受按钮
//            [[EaseMob sharedInstance].contactManager acceptInvitationForUsername:alertView.title];
            EMError *error = nil;
            BOOL isSuccess = [[EaseMob sharedInstance].chatManager acceptBuddyRequest:@"8001" error:&error];
            if (isSuccess && !error) {
                NSLog(@"发送同意成功");
            }
            //点击了接受按钮，说明我们又有了新的朋友，所以应该刷新联系人列表，这里就发送一条广播，通知联系人列表刷新
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshContactsList" object:nil];
        }
    }else{
        //到达登录界面
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        loginVC.state = fromMainViewControllerState;
        UINavigationController *navC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        //当前界面如果为主界面，那么Window的根视图控制器就是mainTabBarController
        [self.window.rootViewController presentViewController:navC animated:YES completion:nil];
    }
}

#pragma mark -- 重连的代理方法
- (void)didConnectionStateChanged:(EMConnectionState)aConnectionState{
    
    /*!
     *  SDK连接服务器的状态变化时会接收到该回调
     *
     *  有以下几种情况, 会引起该方法的调用:
     *  1. 登录成功后, 手机无法上网时, 会调用该回调
     *  2. 登录成功后, 网络状态变化时, 会调用该回调
     *
     *  @param aConnectionState 当前状态
     */
    //    if (aConnectionState == EMConnectionDisconnected) {     //断开连接
    //    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"disConnection" object:nil userInfo:@{@"conn":@(aConnectionState)}];
    //    NSLog(@"无网络连接");
}

#pragma mark -- 被动退出登录
-(void)didLoginFromOtherDevice{
    /** 当前登录账号在其它设备登录时会接收到该回调*/
    NSLog(@"被迫下线！");
    //登录出现问题，由于需要重新登录，所以需要将本地存储的用户信息清空
    CurrentUserInfo *currentUserInfo  = [CurrentUserInfo sharedCurrentUserInfo];
    currentUserInfo.userName = @"";
    currentUserInfo.pwd = @"";
    currentUserInfo.isLogin = NO;
    UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"提示" message:@"此账号在其他设备上登录,账号异常，请重试！ " delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
    /*
     //退回到登录界面
     LoginViewController *loginVC = [[LoginViewController alloc]init];
     
     loginVC.state = fromMainViewControllerState;
     self.mainTabBarController.selectedIndex = 0;
     UINavigationController *navC = [[UINavigationController alloc]initWithRootViewController:loginVC];
     [self.mainTabBarController presentViewController:navC animated:YES completion:nil];
     */
}

-(void)didRemovedFromServer{
    /**当前登录账号已经被从服务器端删除时会收到该回调*/
    //登录出现问题，由于需要重新登录，所以需要将本地存储的用户信息清空
    CurrentUserInfo *currentUserInfo  = [CurrentUserInfo sharedCurrentUserInfo];
    currentUserInfo.userName = @"";
    currentUserInfo.pwd = @"";
    currentUserInfo.isLogin = NO;
    UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"提示" message:@"账号被后台删除，请联系工作人员！ " delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
//app进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
}
//APP将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.SeaCity.Only_Love" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Only_Love" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Only_Love.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
